<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-col :span="4">
        <el-button type="primary" @click="adddialogVisible = true"
          >添加角色</el-button
        >
      </el-col>
      <el-table stripe :data="rolesList" style="width: 100%">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbotttum', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="5">
                <el-tag closable @close="removeRight(scope.row,item1.id)"> {{ item1.authName }}</el-tag
                ><i class="el-icon-caret-right"></i>
              </el-col>

              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6"
                    ><el-tag closable type="success" @close="removeRight(scope.row,item2.id)">{{
                      item2.authName
                    }}</el-tag
                    ><i class="el-icon-caret-right"></i
                  ></el-col>
                  <el-col :span="18"
                    ><el-tag
                      closable
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      @close="removeRight(scope.row,item3.id)"
                      >{{ item3.authName }}</el-tag
                    ></el-col
                  >
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" width="50"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="200">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" width="200">
        </el-table-column>
        <el-table-column prop="" label="操作" width="500">
          <template slot-scope="scope">
            <el-button
              @click="showRous(scope.row.id)"
              type="primary"
              icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button
              @click="deleteRous(scope.row.id)"
              type="danger"
              icon="el-icon-delete"
              >删除</el-button
            >
            <el-button type="warning" icon="el-icon-setting" @click="showRight(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      title="添加用户"
      :visible.sync="adddialogVisible"
      width="50%"
      @close="adddialogClose"
    >
      <el-form
        :model="addForm"
        :rules="addFormrules"
        ref="addFormruleForm"
        label-width="90px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改角色信息"
      :visible.sync="dialogVisible"
      width="50%"
      @close="editClose"
    >
      <el-form
        :model="editForm"
        ref="editFormruleForm"
        label-width="90px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editformrole">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
  title="分配权限"
  :visible.sync="setRightdialogVisible"
  width="50%"
  @close="setRightdialogClose"
  >
  <el-tree
  ref="treeRef"
  :data="setrightList"
  show-checkbox
  node-key="id"
  default-expand-all
  :default-checked-keys="defKye"
  :props="treeProps">
</el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRightdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      adddialogVisible: false,
      dialogVisible: false,
      setRightdialogVisible:false,
      addForm: {
        roleName: "",
        roleDesc: "",
      },
      editForm: {},
      addFormrules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 3, max: 15, message: "长度在 3 到 15个字符", trigger: "blur" },
        ],
      },
      setrightList:[],
      treeProps:{
        label:'authName',
         children: 'children',
      },
      defKye:[],
      roleId:''
    };
  },
  created() {
    this.getrolesList();
  },
  methods: {
    async getrolesList() {
      var { data: resp } = await this.$http.get("roles");
      this.rolesList = resp.data;
    },
    adddialogClose() {
      this.$refs.addFormruleForm.resetFields();
    },
    editClose() {
      this.$refs.editFormruleForm.resetFields();
    },
    addUser() {
      this.$refs.addFormruleForm.validate(async (val) => {
        if (!val) return;
        var { data: resp } = await this.$http.post("roles", this.addForm);
        (this.adddialogVisible = false),
          this.$message({
            type: "success",
            message: "添加成功!",
          });
        this.getrolesList();
      });
    },
    async showRous(id) {
      this.dialogVisible = true;
      var { data: resp } = await this.$http.get("roles/" + id);
      this.editForm = resp.data;
    },
    editformrole() {
      this.$refs.editFormruleForm.validate(async (val) => {
        if (!val) return;
        var { data: resp } = await this.$http.put(
          "roles/" + this.editForm.roleId,
          {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc,
          }
        );
        console.log(resp);
        this.dialogVisible = false;
        this.$message({
          showClose: true,
          message: "更新数据成功",
          type: "success",
        });
        this.getrolesList();
      });
    },
    async deleteRous(id) {
      var con = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        }
      ).catch((err) => err);
      if (con !== "confirm") {
        return this.$message({
          type: "info",
          message: "已取消删除",
        });
      } else {
        var { data: resp } = await this.$http.delete("roles/" + id);
        this.$message({
          type: "success",
          message: "删除成功!",
        });
        this.getrolesList();
      }
    },
    async removeRight(role,rightId){
      var con = await this.$confirm(
        "此操作将永久删除, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        }
      ).catch((err) => err);
      if (con !== "confirm") {
        return this.$message({
          type: "info",
          message: "已取消删除",
        });
      } else {
       var { data: resp } = await this.$http.delete(`roles/${role.id}/rights/${rightId}` );
      }
      role.children =resp.data
    },
    async showRight(role){
      // 获取所有权限
      this.roleId = role.id
     var {data:resp}=await this.$http.get('rights/tree')
     this.setrightList =resp.data
     
     this.getKeys(role,this.defKye)
     this.setRightdialogVisible=true
     
    },
    getKeys(node,arr){
     if (!node.children) {
       return arr.push(node.id)
     }
     node.children.forEach(item =>
     this.getKeys(item,arr)
     )
    },
    setRightdialogClose(){
      this.defKye=[]
    },
    async allotRights(){
      var keys =[
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      var idStr = keys.join(',')
    
    var {data:resp} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
    if (resp.meta.status !==200) {
      return this.$message.error('分配权限失败')
    }else{
      this.$message.success('分配权限成功')
      this.setRightdialogVisible = false;
      this.getrolesList()
    }
    } 
   
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin-top: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbotttum {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
